package com.ziytek.web.citizen.listener;

import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.event.BasicDataEvent;
import com.ziytek.web.citizen.mapper.BasicDataBatchMapper;
import com.ziytek.web.citizen.pojo.BasicDataTable;
import com.ziytek.web.citizen.service.CompressionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;

/**
 * 周期性基础数据保存事件
 *
 * @author fenghx
 * @version 1.0
 * @className BasicDataEvent
 * Description:
 * @date 2024/5/23 15:30
 */

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @__(@Autowired))
public class BasicDataEventListener {

    private final CompressionService compressionService;
    private final BasicDataBatchMapper basicDataBatchMapper;

    @Async("myAsyncExecutor")
    @EventListener
    @Order(NumConstant.INT_ZERO)
    public void basicDataEventListener(BasicDataEvent event) {
        Assert.notNull(event, "basicDataEventListener event is null");
        Assert.notNull(event.getRd(), "basicDataEventListener rd is null");

        var rd = event.getRd();

        // 基础数据保存,先放到缓存,过期了再存入数据库
        var data = new BasicDataTable();
        data.setCabinetNo(rd.getB());

        try {
            data.setBasicData(compressionService.compress(rd.getBd()));
        } catch (IOException e) {
            log.error("basicDataEventListener compress error", e);
            return;
        }

        rd.setBd(null);
        data.setCreateTime(null != rd.getT() ? rd.getTs() : System.currentTimeMillis());
        basicDataBatchMapper.insertData(data);
    }
}
